package com.hsgene.util.mq.rocket.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息处理抽象类，定义消息处理的骨架流程
 *
 * @author wangbing
 * @version 1.0
 * @date 2019/1/16 14:32
 * Copyright: Copyright (c) 2019
 */
public abstract class AbstractRocketMQListener implements IRocketMQListener {

    private final static String SUCCESS_LOG_TEMPLATE = "RocketMQ消息处理【成功】：{}";
    private final static String FAILURE_LOG_TEMPLATE = "RocketMQ消息处理【失败】：{}";

    private final static Logger LOGGER = LoggerFactory.getLogger(AbstractRocketMQListener.class);

    /**
     * 对收到的消息进行记录处理，记录日志（或入库）
     *
     * @param result  处理结果
     * @param message 具体消息内容
     */
    private void doRecord(Action result, Message message) {
        if (consumeSuccess(result)) {
            LOGGER.info(SUCCESS_LOG_TEMPLATE, message);
        } else {
            LOGGER.error(FAILURE_LOG_TEMPLATE, message);
        }
    }

    private boolean consumeSuccess(Action result) {
        return Action.CommitMessage.equals(result);
    }

    /**
     * 消息抽象处理模板方法
     *
     * @param message 消息体
     * @param context 消息上下文
     * @return 处理结果
     */
    public final Action consume(Message message, ConsumeContext context) {
        Action result = Action.CommitMessage;
        try {
            result = this.messageHandler(message);
        } catch (Exception e) {
            result = Action.ReconsumeLater;
            LOGGER.error("消息处理出现异常！");
            e.printStackTrace();
        } finally {
            doRecord(result, message);
        }
        return result;
    }
}
